﻿//---------------------------------------------------------------------
//  Copyright (c) 2012-2013 Daun Project.  All rights reserved.
//  http://daun.codeplex.com
//  http://www.daun-project.com
//---------------------------------------------------------------------

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

using MongoDB.Bson;
namespace Daun.Cores
{
    public class MongoHelpers
    {
        public static BsonType GetBsonType(string type)
        {
            if (Enum.IsDefined(typeof(BsonType), type))
                return (BsonType)Enum.Parse(typeof(BsonType), type, true);
            else
                return BsonType.Undefined;

        }
        public static BsonValue GetBsonValue(string type, object value)
        {
            BsonValue val = null;

            BsonType currentType = GetBsonType(type);
            if (currentType != BsonType.Undefined)
                val = BsonTypeMapper.MapToBsonValue(value, currentType);                     
            
            return val;
        }

        public static void SaveConfiguration(Entities.MongoServerCollection collection)
        {
            string path = string.Format("{0}\\Daun\\", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            if(!Directory.Exists(path))
                Directory.CreateDirectory(path);

            string fileName = string.Format("{0}\\daun.config",path);
            Stream stream = File.Open(fileName, FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, collection);
            stream.Close();
        }
        public static Entities.MongoServerCollection LoadConfiguration()
        {
            string path = string.Format("{0}\\Daun\\", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            string fileName = string.Format("{0}\\daun.config", path);
            if (File.Exists(fileName))
            {
                Entities.MongoServerCollection config;
                Stream stream = File.Open(fileName, FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();
                config = (Entities.MongoServerCollection)formatter.Deserialize(stream);
                stream.Close();

                return config;
            }
            else
                return null;
        }
    }
}
